package cn.edu.zzuli;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Date: 2021/3/6 17:41
 * @Author: 绯色下午茶
 * @Description: 题目，现在两个线程，可以操作初始值为0的一个变量，
 * 实现一个线程对该变量加1，另一个线程对该变量减1
 * 实现交替，10轮
 */
class AirCondirtioner1 {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public  void increment() throws InterruptedException {
        /**
         * 判断需要使用while，不能使用if
         */
        lock.lock();
        try {
            while (number!=0){
                condition.await();
            }
            number++;
            System.out.println(number+"  ***    "+Thread.currentThread().getName());
        }finally {
            lock.unlock();
        }


        condition.signalAll();
    }
    public synchronized void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (number==0){
                condition.await();
            }
            number--;
            System.out.println(number+"  ***    "+Thread.currentThread().getName());

            condition.signalAll();
        }finally {
            lock.unlock();
        }

    }
}

public class ThreadLockDemo {
    public static void main(String[] args) {
        AirCondirtioner airCondirtioner = new AirCondirtioner();

        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airCondirtioner.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airCondirtioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airCondirtioner.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airCondirtioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D ").start();
    }
}
